package com.knowledge.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.knowledge.dao.entity.Article;
import com.knowledge.dao.mapper.ArticleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author zzz
 * @create 2022-02-11 20:12
 */
@Component
@Slf4j
public class ThreadService {


    /**
     * 期望此操作在线程池操作 不会影响原有的主线程
     * @param articleMapper
     * @param article
     */
    @Async("taskExecutor")
    public void updateArticleViewCount(ArticleMapper articleMapper, Article article) {
        int viewCounts = article.getViewCounts();
        Article update = new Article();
        update.setViewCounts(viewCounts+1);
        LambdaQueryWrapper<Article> updateWrapper = new LambdaQueryWrapper<>();
        updateWrapper.eq(Article::getId,article.getId());
        //设置一个 为了在多线程环境下 线程安全 乐观锁 CAS
        updateWrapper.eq(Article::getViewCounts,viewCounts);
        //update article set view_count=100 where view_count=99 and id=11
        articleMapper.update(update,updateWrapper);
        try {
            Thread.sleep(2000);
            log.info("更新完成了...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
